from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from tortoise.contrib.fastapi import register_tortoise
from src.config import get_settings
from src.routers.api_router import api_router
from src.utils.logger import app_logger as logger
from src.schemas import ErrorResponse
from src.services.scheduler_service import scheduler_service
from src.cores.redis import redis_manager
from src.middlewares.auth import add_jwt_auth_middleware
from src.cores.exceptions import (
    CustomException, 
    custom_exception_handler,
    http_exception_handler,
    validation_exception_handler,
    general_exception_handler
)
import time
from datetime import datetime

config = get_settings()

# 创建FastAPI应用
app = FastAPI(
    title=config.APP_NAME,
    version=config.APP_VERSION,
    description=config.APP_DESCRIPTION,
    debug=config.DEBUG_MODE
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=config.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=config.CORS_METHODS,
    allow_headers=config.CORS_HEADERS,
)

# 添加受信任主机中间件（可选）
# if hasattr(config, 'TRUSTED_HOSTS') and config.TRUSTED_HOSTS:
#     app.add_middleware(
#         TrustedHostMiddleware,
#         allowed_hosts=config.TRUSTED_HOSTS
#     )


# 请求日志中间件
@app.middleware("http")
async def log_requests(request: Request, call_next):
    start_time = time.time()
    
    # 记录请求信息
    logger.info(f"请求开始: {request.method} {request.url}")
    
    response = await call_next(request)
    
    # 计算处理时间
    process_time = time.time() - start_time
    
    # 记录响应信息
    logger.info(
        f"请求完成: {request.method} {request.url} - "
        f"状态码: {response.status_code} - 耗时: {process_time:.4f}s"
    )
    
    return response


# 添加异常处理器
app.add_exception_handler(CustomException, custom_exception_handler)  # type: ignore[arg-type]
app.add_exception_handler(HTTPException, http_exception_handler)  # type: ignore[arg-type]
app.add_exception_handler(RequestValidationError, validation_exception_handler)  # type: ignore[arg-type]
app.add_exception_handler(Exception, general_exception_handler)  # type: ignore[arg-type]


# 应用启动事件
@app.on_event("startup")
async def startup_event():
    """应用启动时的初始化"""
    try:
        # 初始化Redis连接
        await redis_manager.init_redis()
        
        # 启动定时任务服务
        scheduler_service.start()
        
        logger.info("应用启动完成")
    except Exception as e:
        logger.error(f"应用启动失败: {e}")
        raise

# 应用关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时的清理"""
    try:
        # 停止定时任务服务
        scheduler_service.stop()
        
        # 关闭Redis连接
        await redis_manager.close_redis()
        
        logger.info("应用关闭完成")
    except Exception as e:
        logger.error(f"应用关闭时出错: {e}")

# 添加JWT认证中间件
if config.ENABLE_JWT_AUTH:
    add_jwt_auth_middleware(app)
    logger.info("JWT鉴权中间件已启用")
else:
    logger.info("JWT鉴权中间件已禁用")

# 注册API路由
app.include_router(api_router, prefix="/api/v1")



# 健康检查接口
@app.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "ok",
        "timestamp": time.time(),
        "version": config.APP_VERSION
    }


# 根路径
@app.get("/")
async def root():
    """根路径"""
    return {
        "message": f"欢迎使用 {config.APP_NAME}",
        "version": config.APP_VERSION,
        "docs": "/docs",
        "redoc": "/redoc"
    }


# 注册数据库
register_tortoise(
    app,
    db_url=f"mysql://{config.MYSQL_USER}:{config.MYSQL_PASS}@{config.MYSQL_HOST}:{config.MYSQL_PORT}/{config.MYSQL_DB}",
    modules={"models": ["src.models"]},
    generate_schemas=True,
    add_exception_handlers=True,
)


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host=config.APP_HOST,
        port=config.APP_PORT,
        reload=config.DEBUG_MODE,
        log_level="info"
    )